Ext.onReady(function(){
    var orderids = ""; //选中的订单编号数组
    var customer_id = "1";
    var ordersrow;
    var current_order_id; //当前选择的order的id
    var current_order_status; //当前order的状态
    setTimeout("refreshDS()", 300000);
    refreshDS = function(){
        var time = parseInt(refreshTime.getValue()) * 60000;
        orderds.reload();
        setTimeout("refreshDS()", time);
    };
    var orderNoField = new Ext.form.TextField({
        fieldLabel: '订单编号',
        name: 'order_no',
        allowBlank: true,
        anchor: '99%'
    });
    var pnrField = new Ext.form.TextField({
        fieldLabel: 'PNR',
        name: 'pnr',
        allowBlank: true,
        anchor: '99%'
    });
    var linkManField = new Ext.form.TextField({
        fieldLabel: '联系人',
        name: 'man',
        allowBlank: true,
        anchor: '99%'
    });
    var linkTelField = new Ext.form.TextField({
        fieldLabel: '联系电话',
        name: 'tel',
        allowBlank: true,
        anchor: '99%'
    });
    var addressField = new Ext.form.TextField({
        fieldLabel: '送票地址',
        name: 'address',
        allowBlank: true,
        anchor: '99%'
    });
    var printStatus = new Ext.form.ComboBox({
        store: new Ext.data.Store({
            reader: new Ext.data.ArrayReader({}, ['value']),
            data: [['所有'], ['未打印'], ['已打印']]
        }),
        name: 'print_status',
        fieldLabel: '订单状态',
        resiable: true,
        typeAhead: true,
        width: 70,
        handleHeight: 100,
        displayField: 'value',
        valueField: 'value',
        nameField: 'print_status',
        selectOnFocus: true,
        mode: 'local',
        selectOnFocus: true,
        triggerAction: 'all', //这个属性非常重要,可以在选择一个值以后,依然还显示其它的值.
        readOnly: true,
        emptyText: '所有类型...',
        allowBlank: true,
        value: '所有'
    });
    var dateField = new Ext.form.DateField({
        fieldLabel: '出票日期',
        name: 'ticket_out_date',
        altFormats: 'Y-m-d',
        format: 'Y-m-d', //格式化日期
        //disabledDays: [0,6],	//不让选择周六，周日
        //disabledDaysText: "周末要休息",
        invalidText: "您输入的日期格式不对，正确格式为2008-01-01",
        allowBlank: false,
        //emptyText: '请选择...',
        inputType: '2008-01-01',
        //anchor: '50%'
        width: 90,
        value: today
    });
    var refreshTime = new Ext.form.ComboBox({
        store: new Ext.data.Store({
            reader: new Ext.data.ArrayReader({}, ['value']),
            data: [['1'], ['5'], ['10'], ['30']]
        }),
        name: 're_time',
        fieldLabel: '刷新间隔(分)',
        resiable: true,
        typeAhead: true,
        width: 60,
        handleHeight: 100,
        displayField: 'value',
        valueField: 'value',
        nameField: 're_time',
        selectOnFocus: true,
        mode: 'local',
        selectOnFocus: true,
        triggerAction: 'all', //这个属性非常重要,可以在选择一个值以后,依然还显示其它的值.
        readOnly: true,
        allowBlank: true,
        value: '5'
    });
    
    //提交按钮
    var submitButton = new Ext.Button({
        text: '查询',
        handler: function(){
            if (formPanel.form.isValid()) {
                var ticket_out_date = dateField.getValue().format('Y-m-d');
                var printed = printStatus.getValue();
                var no = orderNoField.getValue();
                var pnr = pnrField.getValue();
                var man = linkManField.getValue();
                var tel = linkTelField.getValue();
                var address = addressField.getValue();
                //alert(ticket_out_date+"-"+printed+"-"+no+"-"+pnr+"-"+man+"-"+tel+"-"+address);
                orderds.baseParams.printed = printed;
                orderds.baseParams.order_no = no;
                orderds.baseParams.pnr = pnr;
                orderds.baseParams.link_tel = tel;
                orderds.baseParams.link_man = man;
                orderds.baseParams.send_address = address;
                orderds.baseParams.ticket_out_date = ticket_out_date;
                orderds.reload();
            }
            else {
                Ext.MessageBox.alert('提示信息', '请将必填项信息录入后再提交.');
            }
        }
    })
    
    var formPanel = new Ext.form.FormPanel({
        //baseCls: 'x-plain',
        labelWidth: 75,
        width: '100%',
        frame: true,
        title: '打印送票单',
        labelAlign: 'right',
        items: [{
            layout: 'column',
            border: false,
            items: [{
                columnWidth: .2,
                layout: 'form',
                border: false,
                items: [orderNoField]
            }, {
                columnWidth: .15,
                layout: 'form',
                border: false,
                items: [pnrField]
            }, {
                columnWidth: .15,
                layout: 'form',
                border: false,
                items: [linkManField]
            }, {
                columnWidth: .2,
                layout: 'form',
                border: false,
                items: [linkTelField]
            }, {
                columnWidth: .3,
                layout: 'form',
                border: false,
                items: [addressField]
            }]
        }, {
            layout: 'column',
            border: false,
            items: [{
                columnWidth: .2,
                layout: 'form',
                border: false,
                items: [dateField]
            }, {
                columnWidth: .18,
                layout: 'form',
                border: false,
                items: [printStatus]
            }, {
                columnWidth: .18,
                layout: 'form',
                border: false,
                items: [refreshTime]
            }, {
                columnWidth: .3,
                layout: 'form',
                border: false,
                items: [submitButton]
            }]
        }]
    });
    
    formPanel.render('send_ticket_form');
    
    //打印
    printSendTicketInfo = function(){
        //Ext.MessageBox.alert("送票单", "打印");
        if (orderids != "") {
            window.open('/orders/sendTicketWindow?orderids=' + orderids, '', 'scrollbars=yes,width=960,height=500');
        }
        else {
            Ext.MessageBox.alert('提示信息', '没有选择!');
        }
    }
    
    //############## 订单Grid #############
    var sm = new Ext.grid.CheckboxSelectionModel();
    var ordercm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
        header: '编号',
        dataIndex: 'id',
        hidden: true
    }, {
        header: '送票员',
        dataIndex: 'sender',
        width: 60
    }, {
        header: '送票日期',
        dataIndex: 'send_date',
        width: 70
    }, {
        header: '送票时间',
        dataIndex: 'send_time',
        width: 60
    }, {
        header: '送票要求',
        dataIndex: 'send_request',
        width: 100
    }, {
        header: '送票地址',
        dataIndex: 'send_address',
        width: 120
    }, {
        header: '客户要求',
        dataIndex: 'order_request',
        width: 100
    }, {
        header: '订单状态',
        dataIndex: 'status',
        width: 60
    }, {
        header: '乘机日期',
        dataIndex: 'fly_date',
        width: 70
    }, {
        header: '起飞时间',
        dataIndex: 'fly_time',
        width: 60
    }, {
        header: '联系人',
        dataIndex: 'link_man',
        width: 60
    }, {
        header: '联系电话',
        dataIndex: 'link_tel',
        width: 90
    }, {
        header: '订单编号',
        dataIndex: 'order_no',
        width: 120
    }, {
        header: 'PNR',
        dataIndex: 'pnr',
        width: 60
    }, {
        header: '客户名称',
        dataIndex: 'customer',
        width: 70
    }, {
        header: '总金额',
        dataIndex: 'price_sum',
        width: 60
    }, {
        header: '预定员',
        dataIndex: 'creator',
        width: 60,
        hidden: true
    }, {
        header: '预定时间',
        dataIndex: 'created_at',
        width: 110,
        renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
        hidden: true
    }, {
        header: '出票员',
        dataIndex: 'ticket_outer',
        width: 60,
        hidden: true
    }, {
        header: '出票时间',
        dataIndex: 'ticket_out_date',
        width: 110,
        renderer: Ext.util.Format.dateRenderer('Y-m-d H:i'),
        hidden: true
    }, {
        header: '打印状态',
        dataIndex: 'send_printed',
        width: 60
    }, {
        header: '结算类型',
        dataIndex: 'payment_type',
        width: 60
    
    }]);
    ordercm.defaultSortable = true;
    var orderds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/orders/getSendTicketList'
        }),
        reader: orderReader
    });
    
    var menubar = [{
        text: ' 【派单打印】',
        iconCls: 'print',
        handler: function(){
            orderids = "";
            var records = ordergridpanel.getSelectionModel().getSelections();
            if (!records || records.length == 0) {
                Ext.MessageBox.alert('提示信息', '没有选择!');
            }
            else {
                var showFlag = true;
                customer_id = records[0].data['customer_id'];
                current_order_id = records[0].data['id'];
                for (i = 0; i < records.length; i++) {
                    if (i > 0) {
                        if (records[i].data['customer_id'] != records[i - 1].data['customer_id']) {
                            Ext.MessageBox.alert('提示信息', '必须是同一客户的订单才能放到一张送票单里!');
                            showFlag = false;
                            break;
                        }
                        if (records[i].data['send_date'] != records[i - 1].data['send_date']) {
                            Ext.MessageBox.alert('提示信息', '送票日期不同!');
                            showFlag = false;
                            break;
                        }
                        if (records[i].data['send_address'] != records[i - 1].data['send_address']) {
                            Ext.MessageBox.alert('提示信息', '必须是送票地址一致的订单才能放到一张送票单里!');
                            showFlag = false;
                            break;
                        }
                    }
                    var for_order_id = records[i].data['id'];
                    if (i == 0) {
                        orderids += for_order_id;
                    }
                    else {
                        orderids += "," + for_order_id;
                    }
                //alert(records[i].data['id'] + "---" + records[i].data['send_address']);
                }
                if (showFlag) {
                    sendDetail();
                }
            }
        }
    /*
         }, '-', {
         text: '打印送票单',
         handler: function(){
         orderids = "";
         var records = ordergridpanel.getSelectionModel().getSelections();
         if (!records || records.length == 0) {
         Ext.MessageBox.alert('提示信息', '没有选择!');
         }
         else {
         var showFlag = true;
         customer_id = records[0].data['customer_id'];
         current_order_id = records[0].data['id'];
         for (i = 0; i < records.length; i++) {
         if (i > 0) {
         if (records[i].data['customer_id'] != records[i - 1].data['customer_id']) {
         Ext.MessageBox.alert('提示信息', '必须是同一客户的订单才能放到一张送票单里!');
         showFlag = false;
         break;
         }
         if (records[i].data['send_date'] != records[i - 1].data['send_date']) {
         Ext.MessageBox.alert('提示信息', '送票日期不同!');
         showFlag = false;
         break;
         }
         if (records[i].data['send_address'] != records[i - 1].data['send_address']) {
         Ext.MessageBox.alert('提示信息', '必须是送票地址一致的订单才能放到一张送票单里!');
         showFlag = false;
         break;
         }
         }
         var for_order_id = records[i].data['id'];
         if (i == 0) {
         orderids += for_order_id;
         }
         else {
         orderids += "," + for_order_id;
         }
         //alert(records[i].data['id'] + "---" + records[i].data['send_address']);
         }
         if (showFlag) {
         printSendTicketInfo();
         }
         }
         }
         */
    }];
    
    var ordergridpanel = new Ext.grid.GridPanel({
        el: 'ordersgrid',
        ds: orderds,
        cm: ordercm,
        sm: sm,
        loadMask: true,
        autoWidth: true,
        collapsible: true,
        animCollapse: true,
        height: 330,
        title: '订单信息',
        tbar: menubar
    });
    
    ordergridpanel.render();
    orderds.load();
    
    //双击订单查看票详细
    ordergridpanel.on('rowdblclick', function(ordergridpanel, rowIndex, e){
        var current_order_selected = orderds.data.items[rowIndex].id;
        ordersrow = orderds.getById(current_order_selected);
        current_order_id = ordersrow.get("id");
        current_order_status = ordersrow.get("status");
        ticketds.baseParams.id = current_order_id;
        ticketds.reload();
    });
    //订单右键菜单
    ordergridpanel.on('rowcontextmenu', function(customergridpanel, rowIndex, e){
        var current_order_selected = orderds.data.items[rowIndex].id;
        ordersrow = orderds.getById(current_order_selected);
        current_order_id = ordersrow.get("id");
        current_order_status = ordersrow.get("status");
        e.preventDefault();
        rightClick.showAt(e.getXY());
    });
    
    //############ 订单-右键菜单 ##########
    var rightClick = new Ext.menu.Menu({
        items: [{
            handler: rightMenu1Fn,
            text: '【提取PNR】'
        }, {
            handler: rightMenu2Fn,
            text: '【查看客户】'
        }]
    });
    function rightMenu1Fn(){
        showPnrInfo(current_order_id);
    }
    function rightMenu2Fn(){
        var customer_id = ordersrow.get("customer_id");
        showCustomerInfo(customer_id);
    }
    
    //********* Form 送票属性 ************
    var fixWindow;
    function sendDetail(){
        if (fixWindow) {
            //fixWindow.close();
            fixWindow.hide();
        }
        var link_man = new Ext.form.TextField({
            fieldLabel: '联系人',
            name: 'link_man',
            allowBlank: false,
            blankText: "联系人不允许为空",
            anchor: '90%'
        });
        var link_tel = new Ext.form.TextField({
            fieldLabel: '联系人电话',
            name: 'link_tel',
            allowBlank: false,
            blankText: "联系电话不允许为空",
            anchor: '90%'
        });
        //送票地址关键字搜索
        var address_resultTpl = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<h3>{address}</h3>', '</div></tpl>');
        var send_address = new Ext.form.ComboBox({
            store: new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({
                    url: '/customers/getAddressComboBox?id=' + customer_id
                }),
                reader: new Ext.data.JsonReader({
                    root: 'root'
                }, [{
                    name: 'address'
                }])
            }),
            fieldLabel: '送票地址',
            name: 'send_address',
            allowBlank: false,
            blankText: "送票地址不允许为空",
            anchor: '90%',
            //value: '',
            displayField: 'address',
            typeAhead: false,
            loadingText: 'Searching...',
            //width: 250,
            hideTrigger: false,
            tpl: address_resultTpl,
            //transform: 'send_address_el',
            //applyTo: 'send_address_el',
            minChars: 0,
            itemSelector: 'div.search-item',
            onSelect: function(record){
                //alert(record.data.address);
                send_address.setValue(record.data.address);
                if (this.isExpanded()) {
                    this.collapse();
                }
            }
        });
        var send_date = new Ext.form.DateField({
            fieldLabel: '送票日期',
            name: 'send_date',
            altFormats: 'Y-m-d',
            format: 'Y-m-d', //格式化日期
            //disabledDays: [0,6],	//不让选择周六，周日
            //disabledDaysText: "周末要休息",
            invalidText: "您输入的日期格式不对，正确格式为2008-01-01",
            allowBlank: false,
            blankText: "送票日期不允许为空",
            //emptyText: '请选择...',
            inputType: '2008-01-01',
            //anchor: '50%'
            width: 100
        });
        var send_time = new Ext.form.TimeField({
            fieldLabel: '送票时间',
            name: 'send_time',
            altFormats: 'H:i',
            format: 'H:i',
            increment: 30,
            minValue: SEND_START_TIME,
            maxValue: SEND_END_TIME,
            allowBlank: false,
            blankText: "送票时间不允许为空",
            //anchor: '50%'
            width: 80
        });
        var send_request = new Ext.form.TextField({
            fieldLabel: '送票要求',
            name: 'send_request',
            allowBlank: true,
            anchor: '90%'
        });
        var sender = new Ext.form.ComboBox({
            store: new Ext.data.Store({
                proxy: new Ext.data.HttpProxy({
                    url: '/users/getSendersComboBox'
                }),
                reader: new Ext.data.JsonReader({
                    root: 'root'
                }, ['id', 'user_name'])
            }),
            fieldLabel: '送票人',
            name: 'sender',
            loadingText: '正在加载...',
            displayField: 'user_name',
            valueField: 'id',
            mode: 'remote',
            //hideTrigger: true,
            triggerAction: 'all',
            hiddenName: 'sender',//如果不想提交displayField，则在这儿指定以提交ID的值．
            //hiddenId:'sender',
            //emptyText: '请选择...',
            editable: false,
            allowBlank: false,
            blankText: "送票人必须选择",
            //forceSelection: false,
            width: 100,
            //maxHeight: 150,
            tabIndex: 4
        /*
             ,
             listeners: {
             select: function(combo, record, index){
             //cityCombo.clearValue();
             //cityCombo.store.loadData(record.data.city);
             }
             }
             */
        });
        var printField = new Ext.form.ComboBox({
            store: new Ext.data.Store({
                reader: new Ext.data.ArrayReader({}, ['value']),
                data: [['已打印'], ['未打印']]
            }),
            name: 'send_printed',
            fieldLabel: '打印状态',
            resiable: true,
            typeAhead: true,
            width: 100,
            handleHeight: 100,
            displayField: 'value',
            valueField: 'value',
            nameField: 'status',
            selectOnFocus: true,
            mode: 'local',
            selectOnFocus: true,
            triggerAction: 'all', //这个属性非常重要,可以在选择一个值以后,依然还显示其它的值.
            readOnly: true,
            emptyText: '选择类型...',
            allowBlank: true,
            value: '已打印'
        });
        var formPanel = new Ext.form.FormPanel({
            //baseCls: 'x-plain',
            labelWidth: 70,
            labelAlign: 'right',
            frame: true,
            width: 390,
            //title: '订票',
            url: "/orders/saveSendInfo?orderids=" + orderids,
            reader: new Ext.data.JsonReader({
                root: 'root'
            }, ['link_man', 'link_tel', 'send_address', {
                name: 'send_date',
                type: 'date',
                dateFormat: 'Y/m/d'
            }, 'send_time', 'send_request', {
                name: 'sender',
                mapping: 'sender.user_name'
            }]),
            items: [printField, sender, {
                xtype: 'fieldset',
                checkboxToggle: true,
                //collapsible: true,
                checkboxName: 'checkbox_send',
                title: '送票',
                autoHeight: true,
                //defaults: {width: 210},
                defaultType: 'textfield',
                collapsed: false,
                items: [link_man, link_tel, send_address, send_date, send_time, send_request]
            }]
        });
        
        formPanel.form.load({
            url: '/orders/getSendTicketInfo?id=' + current_order_id,
            waitMsg: '正在载入数据...',
            success: function(form, action){
            //Ext.MessageBox.alert('提示信息', '信息加载成功！');
            },
            failure: function(form, action){
                Ext.MessageBox.alert('提示信息', '信息加载失败');
            }
        });
        
        //送票信息窗口
        fixWindow = new Ext.Window({
            title: '确认送票信息',
            width: 390,
            height: 330,
            layout: 'fit',
            plain: true,
            bodyStyle: 'padding:5px;',
            buttonAlign: 'center',
            items: formPanel,
            buttons: [{
                text: '保存',
                handler: function(){
                    if (formPanel.form.isValid()) {
                        formPanel.form.submit({
                            waitMsg: 'In processing',
                            success: function(form, action){
                                var info = "操作失败，具体失败原因请查询系统日志";
                                if (action.result && action.result.info && action.result.info != "") {
                                    info = action.result.info;
                                }
                                Ext.MessageBox.alert('操作信息', info);
                                if (info.indexOf("成功") >= 0) {
                                    //fixWindow.hide();
                                    orderds.reload();
                                }
                            },
                            failure: function(form, action){
                                var info = "操作失败，具体失败原因请查询系统日志";
                                if (action.result && action.result.info && action.result.info != "") {
                                    info = action.result.info;
                                }
                                Ext.MessageBox.alert('操作信息', info);
                            }
                        });
                    }
                    else {
                        Ext.MessageBox.alert('错误消息', '请将必填项信息录入后再提交.');
                    }
                }
            }, {
                text: '打印',
                handler: function(){
                    if (formPanel.form.isValid()) {
                    
                        printSendTicketInfo();
                    }
                    else {
                        Ext.MessageBox.alert('错误消息', '送票信息不全，请填写保存后再打印.');
                    }
                }
            }, {
                text: '取消',
                handler: function(){
                    fixWindow.hide();
                }
            }]
        });
        fixWindow.show();
    }
    
    //### 机票Grid ###
    var ticketcm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), {
        header: '编号',
        dataIndex: 'id',
        hidden: true
    }, {
        header: 'PNR',
        dataIndex: 'pnr',
        width: 60
    }, {
        header: '旅客姓名',
        dataIndex: 'passenger_name',
        width: 70
    }, {
        header: '证件号码',
        dataIndex: 'card',
        width: 140
    }, {
        header: '票号',
        dataIndex: 'ticket_no',
        width: 110
    }, {
        header: '状态',
        dataIndex: 'status_type',
        width: 50
    }, {
        header: '出票状态',
        dataIndex: 'status',
        sortable: true,
        width: 60
    }, {
        header: '航班号',
        dataIndex: 'air_no',
        width: 60
    }, {
        header: '航程',
        dataIndex: 'fromto',
        width: 60
    }, {
        header: '乘机日期',
        dataIndex: 'fly_date',
        width: 70
    }, {
        header: '起飞时间',
        dataIndex: 'fly_time',
        width: 60
    }, {
        header: '舱位',
        dataIndex: 'position',
        width: 40
    }, {
        header: '机票价格',
        dataIndex: 'price',
        width: 60
    }, {
        header: '机场费税',
        dataIndex: 'airdrome_tax',
        width: 60
    }, {
        header: '附加费',
        dataIndex: 'fuel_tax',
        width: 60
    }, {
        header: 'F',
        dataIndex: 'price_F',
        width: 40
    }, {
        header: '保险份数',
        dataIndex: 'insurance_number',
        width: 60
    }, {
        header: '保险F',
        dataIndex: 'insurance_F',
        width: 50
    }, {
        header: '其他',
        dataIndex: 'other',
        width: 50
    }, {
        header: '积分',
        dataIndex: 'point',
        width: 50
    }, {
        header: '合计',
        dataIndex: 'total_price',
        width: 60
    
    }]);
    ticketcm.defaultSortable = true;
    var ticketds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/orders/getTicketsByOrderID?showCancelTicket=no'
        }),
        reader: ticketReader
    });
    
    var ticketgridpanel = new Ext.grid.GridPanel({
        el: 'ticketsgrid',
        ds: ticketds,
        cm: ticketcm,
        loadMask: true,
        autoWidth: true,
        collapsible: true,
        animCollapse: false,
        height: 180,
        //frame: true,
        title: '航班信息'
    });
    
    ticketgridpanel.render();
    ticketds.load();
})
